package com.example.http.consumer.client;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.http.consumer.bean.User;
import com.example.http.consumer.common.Result;

import java.io.IOException;

public class JSONClient {

    private static final String PREFIX_URL = "http://localhost:8070/provider/jsonServlet";

    public static void main(String[] args) throws IOException {
        JSONClient jsonClient = new JSONClient();
        System.out.println("jsonClient.get ---> " + jsonClient.get(1));
        User user = new User("json", 15);
        System.out.println("jsonClient.add ---> " + jsonClient.add(user));
    }

    public User add(User user) throws IOException {
        String urlString = PREFIX_URL + "?requestType=add";
        Result<User> result = JSON.parseObject(postRequest(urlString, user), new TypeReference<Result<User>>() {
        });
        return result.getData();
    }

    public User get(Integer id) throws IOException {
        String urlString = PREFIX_URL + "?requestType=get&id=" + id;
        Result<User> result = JSON.parseObject(postRequest(urlString, null), new TypeReference<Result<User>>() {
        });
        return result.getData();
    }

    private String postRequest(String urlString, Object data) throws IOException {
        return HttpUtil.createRequest(Method.POST, urlString)
                .body(JSON.toJSONString(data))
                .execute()
                .body();
    }
}
